package com.netease.videoLoaderDemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Rect;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class SpriteImageHelper {

    private static String TAG = "SpriteImageHelper";

    private static SpriteImageHelper instance;
    private Handler mHandler;
    private HandlerThread mHandlerThread;

    private SpriteImageHelper() {
    }

    public static SpriteImageHelper getInstance() {
        if (instance == null) {
            instance = new SpriteImageHelper();
            instance.init();
        }
        return instance;
    }
    private void init(){
        if(mHandlerThread == null){
            mHandlerThread = new HandlerThread("workerthread");
            mHandlerThread.start();
            mHandler = new Handler(mHandlerThread.getLooper());
        }
    }
    private void postRunnableIfNotExists(Runnable runnable) {
        if (mHandler != null) {
            if (!mHandler.hasMessages(0)) { // 检查 HandlerThread 是否正在执行任务
                mHandler.post(runnable); // 如果 HandlerThread 没有正在执行任务，则投递新任务
            }
        }
    }

    /**
     * 下载雪碧图
     * @param context
     * @param imfo 雪碧图信息
     */
    public void downloadThumbs(Context context, SpriteImageInfo imfo){
        File dir = new File(context.getCacheDir().getAbsolutePath() + "/thumb/");
        if (!dir.exists()) {
            dir.mkdirs(); // 创建文件夹
        }
        //判断是否需要下载
        boolean needDownload = false;
        for(int i = 0; i < imfo.storeUrls.size(); i++) {
            String imageUrl = imfo.storeUrls.get(i);
            String path = dir.getAbsolutePath() + md5(imageUrl) + ".jpg";
            File imageFile = new File(path);
            if (!imageFile.exists()) {
                needDownload = true;
            }
        }
        if(needDownload) {
            postRunnableIfNotExists(() -> {
                for (int i = 0; i < imfo.storeUrls.size(); i++) {
                    String imageUrl = imfo.storeUrls.get(i);
                    String path = dir.getAbsolutePath() + md5(imageUrl) + ".jpg";
                    File imageFile = new File(path);
                    if (!imageFile.exists()) {
                        try {
                            URL url = new URL(imageUrl);
                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                            connection.setRequestMethod("GET");

                            InputStream inputStream = new BufferedInputStream(connection.getInputStream());
                            byte[] data = new byte[1024];
                            int count;
                            FileOutputStream outputStream = new FileOutputStream(path);
                            while ((count = inputStream.read(data)) != -1) {
                                outputStream.write(data, 0, count);
                            }
                            outputStream.close();
                            inputStream.close();
                            connection.disconnect();
                        } catch (IOException e) {
                            Log.e(TAG, "Error downloading image: " + e.getMessage());
                        }
                    }
                }
            });
        }
    }

    /**
     * 根据播放位置 postion 和雪碧图 Interval 计算出缩略小图在雪碧图中的 index。
     * @param imfo 雪碧图信息
     * @param position 播放位置 单位ms
     * @return
     */
    public int getCurrentThumbIndex(SpriteImageInfo imfo, final long position){
        if(imfo.interval == 0){
            return 0;
        }
        return (int) (position / 1000 / imfo.interval);
    }

    /**
     * 根据播放位置 position 和雪碧图信息 imfo 获取缩略小图
     * @param context context
     * @param imfo 雪碧图信息
     * @param index 缩略小图在雪碧图中的 index，通过 getCurrentThumbIndex 获取
     * @return
     */
    public Bitmap getThumbBitmap(Context context, SpriteImageInfo imfo, int index) {
        if (context == null || imfo.rows == 0 || imfo.columns == 0 || imfo.interval == 0) {
            return null;
        }

        Rect rect = new Rect();
        int spriteIndex = index / (imfo.rows * imfo.columns);
        // 缩略小图在雪碧大图中的 index
        index = index % (imfo.rows * imfo.columns);
        rect.left = (index % imfo.columns) * (imfo.width / imfo.columns);
        rect.top = (index / imfo.columns) * (imfo.height / imfo.rows);
        rect.right = rect.left + (imfo.width / imfo.columns);
        rect.bottom = rect.top + (imfo.height / imfo.rows);
        try {
            File dir = new File(context.getCacheDir().getAbsolutePath() + "/thumb/");
            String path = dir.getAbsolutePath() + md5(imfo.storeUrls.get(spriteIndex)) + ".jpg" ;
            BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(path, false);
            Bitmap decodeBitmap = decoder.decodeRegion(rect, null);
            decoder.recycle();
            return decodeBitmap;
        } catch (Exception e) {
            Log.d(TAG, "getThumbBitmap Exception " + e);
        }
        return null;
    }

    private String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            // Convert the byte array to a hexadecimal string
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

}
